using Digitalmes.Domain.Entities.Mes.Equipments;
using Digitalmes.Domain.Entities.Mes.Masters;

namespace Digitalmes.Application.Mes.Equipments.StandardParts.Queries;

/// <summary>
/// 设备点检标件分页查询命令。
/// </summary>
public sealed record GetStandardPartsListWithPagedQuery(
    long? LineId,
    string? PartNo,
    string? PartName,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<EquipInspectionStandardPartsDto>>>;

internal sealed class GetStandardPartsListWithPagedQueryHandler(IRepository<EquipInspectionStandardParts> repo, IRepository<MdWorkstation> workstationRepo)
    : IRequestHandler<GetStandardPartsListWithPagedQuery, IResult<PagedList<EquipInspectionStandardPartsDto>>>
{
    public async Task<IResult<PagedList<EquipInspectionStandardPartsDto>>> Handle(GetStandardPartsListWithPagedQuery request, CancellationToken cancellationToken)
    {
        var items = await repo.AsQueryable()
            .Includes(m => m.Line)
            .WhereIF(request.LineId > 0, m => m.LineId == request.LineId)
            .WhereIF(!string.IsNullOrWhiteSpace(request.PartNo), m => m.StandardPartNo.Contains(request.PartNo!))
            .WhereIF(!string.IsNullOrWhiteSpace(request.PartName), m => m.StandardPartName.Contains(request.PartName!))
            .GetPagedListAsync(request.PageNumber, request.PageSize, cancellationToken);

        // 考虑 orm 是否可以 Includes 集合属性，属性指定的字段也是集合
        var items0 = items.Adapt<PagedList<EquipInspectionStandardPartsDto>>();
        if (items0.TotalPages > 0)
        {
            var standardParts1 = items0.Items.Where(s => s.WorkstationIds?.Length > 0);
            var workstationIds = standardParts1.SelectMany(s => s.WorkstationIds!).ToArray();
            var workstations2 = await workstationRepo.GetListAsync(m => workstationIds.Contains(m.Id), cancellationToken);

            foreach (var item in standardParts1)
            {
                item.WorkstationCodes = workstations2.Where(s => item.WorkstationIds!.Contains(s.Id)).Select(m => m.WsCode).ToArray();
            }
        }
    
        return Result.From(items0);
    }
}
